package com.jcbase.controller.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import com.jcbase.core.auth.anno.RequiresPermissions;
import com.jcbase.core.controller.JCBaseController;
import com.jcbase.core.model.Condition;
import com.jcbase.core.model.Operators;
import com.jcbase.core.util.CommonUtils;
import com.jcbase.core.util.JqGridModelUtils;
import com.jcbase.core.util.WeiXinUtils;
import com.jcbase.core.weixin.interceptor.ApiInterceptor;
import com.jcbase.core.weixin.menu.Button;
import com.jcbase.core.weixin.menu.ComButton;
import com.jcbase.core.weixin.menu.Menu;
import com.jcbase.model.RisebdWechatMenu;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.MenuApi;

public class WechatMenuController extends JCBaseController {
	private Logger logger = Logger.getLogger(getClass());

	@RequiresPermissions(value = { "/sys/wechat/menu" })
	public void index() {
		render("wechat_menu_index.jsp");
	}

	@RequiresPermissions(value = { "/sys/wechat/menu" })
	public void add() {
		Integer id = getParaToInt("id");
		logger.info("请求参数id=" + id);
		if (id != null) {
			RisebdWechatMenu risebdWechatMenu = RisebdWechatMenu.me.getById(id);
			if (risebdWechatMenu != null) {
				Integer pid = (Integer) risebdWechatMenu.getInt("parent_id");
				if (pid != null) {// 获取父资源
					RisebdWechatMenu pRes = RisebdWechatMenu.me.getById(pid);
					setAttr("pRes", pRes);
				}
			}
			setAttr("wechatMenu", risebdWechatMenu);
		} else {
			setAttr("jsonTree", JsonKit.toJson(RisebdWechatMenu.me.getZtreeViewList()));
		}
		this.renderJsp("wechat_menu_add.jsp");
	}

	public void getListData() {
		String name = this.getPara("name");
		Set<Condition> conditions = new HashSet<Condition>();
		if (CommonUtils.isNotEmpty(name)) {
			conditions.add(new Condition("name", Operators.LIKE, name));
		}
		Page<RisebdWechatMenu> pageInfo = RisebdWechatMenu.me.getPage(getPage(), this.getRows(), conditions,
				this.getOrderby());
		this.renderJson(JqGridModelUtils.toJqGridView(pageInfo));
	}

	@RequiresPermissions(value = { "/sys/wechat/menu" })
	public void saveRes() {
		Integer id = getParaToInt("id");
		Integer parent_id = getParaToInt("parent_id");
		String parent_name = getPara("parent_name");
		Integer orders = getParaToInt("orders");
		String name = getPara("name");
		String url = getPara("url");
		int result = RisebdWechatMenu.me.saveRes(id, name, parent_id, parent_name, url, orders);
		Map<String, Object> mapData = new HashMap<String, Object>();
		mapData.put("code", "success");
		if (result == 1) {
			mapData.put("result", "添加成功！！");
		} else if (result == 2) {
			mapData.put("result", "编辑成功！！");
		}
		this.renderJson(mapData);
	}

	@RequiresPermissions(value = { "/sys/wechat/menu" })
	public void delete() {
		Integer id = getParaToInt("id");
		boolean result = RisebdWechatMenu.me.deleteById(id);
		Map<String, Object> mapData = new HashMap<String, Object>();
		mapData.put("code", "success");
		if (result) {
			mapData.put("result", "删除成功！！");
		} else {
			mapData.put("result", "删除失败！！");
		}
		this.renderJson(mapData);
	}

	// 微信菜单管理
	@RequiresPermissions(value = { "/sys/wechat/menu" })
	@Before(ApiInterceptor.class)
	public void create() {
		// 父级菜单
		List<RisebdWechatMenu> parentWeChatMenus = RisebdWechatMenu.me.getParent();
		if (null != parentWeChatMenus && parentWeChatMenus.size() > 0 && parentWeChatMenus.size() <= 3) {
			List<Button> buttons = new ArrayList<Button>();
			for (RisebdWechatMenu wechatMenu : parentWeChatMenus) {
				Integer parentId = wechatMenu.getInt("id");
				// 查找子级菜单
				List<RisebdWechatMenu> childLaundryWeChatMenus = RisebdWechatMenu.me.getByParentId(parentId);
				if (null == childLaundryWeChatMenus || childLaundryWeChatMenus.size() == 0) {
					// 没有子级菜单
					Button button = WeiXinUtils.getButton(wechatMenu.getType(), wechatMenu.getName(),
							wechatMenu.getKey(), wechatMenu.getUrl());
					buttons.add(button);
				} else {
					// 有子级菜单
					ComButton comButton = new ComButton();
					List<Button> childButtons = new ArrayList<Button>();
					for (RisebdWechatMenu laundryWeChatMenu2 : childLaundryWeChatMenus) {
						Button button = WeiXinUtils.getButton(laundryWeChatMenu2.getType(),
								laundryWeChatMenu2.getName(), laundryWeChatMenu2.getKey(), laundryWeChatMenu2.getUrl());
						childButtons.add(button);
					}
					// 父级菜单名称
					String name = wechatMenu.getStr("name");
					comButton.setName(name);
					comButton.setSub_button(childButtons.toArray(new Button[childButtons.size()]));
					buttons.add(comButton);
				}
			}
			Menu menu = new Menu();
			menu.setButton(buttons.toArray(buttons.toArray(new Button[buttons.size()])));
			String jsonMenu = JsonKit.toJson(menu).toString();
			ApiResult apiResult = MenuApi.createMenu(jsonMenu);
			System.out.println(apiResult);
			renderJson(apiResult.getJson());
		} else {
			// 参数不正常
		}
	}
}
